<template>
    <view>
        <TopNavigation title="赛程结算方式管理" backText="赛程模式管理" />
        <view class="view-container">
            <view class="view-container-right">
                <view class="view-container-right-add" @click="openAddSettleModal">
                    <text>添加结算方式</text>
                </view>
                <BoxView :titBoxObj="{
                    title: '结算方式列表',
                    titleCount: `共有${settleList.length}个结算方式`
                }" padding="0" style="background: #FFFFF4;">
                    <view class="view-container-right-list">
                        <view class="view-container-right-list-item-empty"
                            v-if="settleList.length === 0 && !isAddingNewSettle && !loading">
                            <text>暂无结算方式</text>
                        </view>
                        <view class="view-container-right-list-item-empty" v-if="loading">
                            <text>加载中...</text>
                        </view>
                        <!-- 新增结算方式表单 -->
                        <view v-if="isAddingNewSettle"
                            class="view-container-right-list-item view-container-right-list-add">
                            <view class="view-container-right-list-item-title">
                                <view class="next-row">
                                    <view class="id-value" style="width: 50%;">
                                        <text class="form-label">结算类型：</text>
                                        <input v-model="settleForm.settleType" placeholder="请输入结算类型"
                                            class="form-input" />
                                    </view>
                                    <view class="id-text" style="width: 50%;">
                                        <text class="form-label">结算名称：</text>
                                        <input v-model="settleForm.settleName" placeholder="请输入结算名称" class="form-input" />
                                    </view>
                                </view>
                                <view class="next-row">
                                    <view class="id-text" style="width: 100%;">
                                        <text class="form-label">结算描述：</text>
                                        <textarea v-model="settleForm.settleDesc" placeholder="请输入结算描述"
                                            class="form-textarea" rows="3" />
                                    </view>
                                </view>
                                <view class="next-button">
                                    <view class="next-button-item1" @click.stop="saveSettle">提交</view>
                                    <view class="next-button-item2" @click.stop="cancelAddSettle">取消</view>
                                </view>
                            </view>
                        </view>
                        <view v-if="!loading && settleList.length > 0" class="view-container-right-list-item"
                            :class="{ 'view-container-right-list-item-editing': editingSettleId === settle.id }"
                            v-for="settle in settleList" :key="settle.id">
                            <view class="view-container-right-list-item-title">
                                <!-- 编辑状态 -->
                                <template v-if="editingSettleId === settle.id">
                                    <view class="next-row">
                                        <view class="id-text"><text class="settle-id-disabled">方式ID：</text><text class="settle-id-disabled">{{ settle.id }}</text></view>
                                    </view>
                                    <view class="next-row">
                                        <view class="id-value" style="width: 50%;">
                                            <text class="form-label">结算类型：</text>
                                            <input v-model="settleForm.settleType" placeholder="请输入结算类型" class="form-input" />
                                        </view>
                                        <view class="id-text" style="width: 50%;">
                                            <text class="form-label">结算名称：</text>
                                            <input v-model="settleForm.settleName" placeholder="请输入结算名称" class="form-input" />
                                        </view>
                                    </view>
                                    <view class="next-row">
                                        <view class="id-text" style="width: 100%;">
                                            <text class="form-label">结算描述：</text>
                                            <textarea v-model="settleForm.settleDesc" placeholder="请输入结算描述"
                                                class="form-textarea" rows="3" />
                                        </view>
                                    </view>
                                    <view class="next-button">
                                        <view class="next-button-item1" @click.stop="saveSettle">保存</view>
                                        <view class="next-button-item2" @click.stop="cancelEditSettle">取消</view>
                                    </view>
                                </template>
                                <!-- 查看状态 -->
                                <template v-else>
                                    <view class="next-row">
                                        <view class="id-text"><text>方式ID：</text>{{ settle.id }}</view>
                                    </view>
                                    <view class="next-row">
                                        <view class="id-value"><text>结算类型：</text>{{ settle.settleType || '未设置' }}</view>
                                        <view class="id-text"><text>结算名称：</text>{{ settle.settleName || '未设置' }}</view>
                                    </view>
                                    <view class="next-row">
                                        <view class="id-text" style="width: 100%;"><text>结算描述：</text>{{ settle.settleDesc || '未设置' }}</view>
                                    </view>
                                    <view class="next-row">
                                        <view class="id-text"><text>创建时间：</text>{{ formatDate(settle.createTime) }}</view>
                                    </view>
                                    <view class="next-button">
                                        <view class="next-button-item1" @click.stop="editSettle(settle)">编辑</view>
                                        <view class="next-button-item2" @click.stop="deleteSettle(settle)">删除</view>
                                    </view>
                                </template>
                            </view>
                        </view>
                    </view>

                </BoxView>
            </view>
        </view>
        
        <!-- 删除确认弹窗 -->
        <PopuleView
            v-model="showDeleteConfirm"
            title="确认删除"
            :description="deleteConfirmText"
            :show-submit="true"
            submit-text="确认删除"
            @submit="confirmDelete"
        />
    </view>

</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { MatchScheduleSettleAPI } from '@/api/battle.js'
import BoxView from "@/components/UiView/BoxView.vue";
import TopNavigation from "@/components/UiView/TopNavigation.vue";
import PopuleView from "@/components/UiView/PopuleView.vue";

const loading = ref(false)
const settleList = ref([])

// 结算方式表单相关数据
const submitting = ref(false)
const isEditingSettle = ref(false)
const currentSettle = ref(null)
const editingSettleId = ref(null) // 正在编辑的结算方式ID

// 新增结算方式相关
const isAddingNewSettle = ref(false)

// 删除确认弹窗
const showDeleteConfirm = ref(false)
const currentDeleteSettle = ref(null)
const deleteConfirmText = computed(() => {
    if (!currentDeleteSettle.value) return ''
    const settleId = currentDeleteSettle.value.id
    const settleName = currentDeleteSettle.value.settleName || settleId
    return `确定要删除结算方式 "${settleName}" 吗？`
})

// 结算方式表单数据
const settleForm = ref({
    matchScheduleSettleId: '',
    settleType: '',
    settleName: '',
    settleDesc: ''
})

const formatDate = (timestamp) => {
    if (!timestamp) return '未设置'
    const date = new Date(timestamp)
    return date.toLocaleString('zh-CN')
}

// 加载结算方式列表
const loadSettleList = async () => {
    loading.value = true
    try {
        const result = await MatchScheduleSettleAPI.page({
            pageNum: 0,
            pageSize: 100
        })
        
        if (result.code === 0 && result.data) {
            settleList.value = result.data.list || result.data || []
        } else {
            settleList.value = []
            throw new Error(result.msg || '获取结算方式列表失败')
        }
    } catch (error) {
        console.error('获取结算方式列表失败:', error)
        uni.showToast({
            title: error.message || '获取结算方式列表失败',
            icon: 'none'
        })
    } finally {
        loading.value = false
    }
}

// 打开添加结算方式表单
const openAddSettleModal = () => {
    isAddingNewSettle.value = true
    resetSettleForm()
}

// 取消添加结算方式
const cancelAddSettle = () => {
    isAddingNewSettle.value = false
    resetSettleForm()
}

// 打开编辑结算方式
const editSettle = (settle) => {
    editingSettleId.value = settle.id
    currentSettle.value = settle
    fillSettleForm(settle)
    isEditingSettle.value = true
}

// 取消编辑结算方式
const cancelEditSettle = () => {
    editingSettleId.value = null
    currentSettle.value = null
    isEditingSettle.value = false
    resetSettleForm()
}

// 重置结算方式表单
const resetSettleForm = () => {
    settleForm.value = {
        matchScheduleSettleId: '',
        settleType: '',
        settleName: '',
        settleDesc: ''
    }
}

// 填充结算方式表单
const fillSettleForm = (settle) => {
    settleForm.value = {
        matchScheduleSettleId: settle.id || settle.matchScheduleSettleId,
        settleType: settle.settleType || '',
        settleName: settle.settleName || '',
        settleDesc: settle.settleDesc || ''
    }
}

// 保存结算方式
const saveSettle = async () => {
    // 表单验证
    const settleType = String(settleForm.value.settleType || '').trim()
    const settleName = String(settleForm.value.settleName || '').trim()
    
    if (!settleType) {
        uni.showToast({
            title: '请输入结算类型',
            icon: 'none'
        })
        return
    }
    
    if (!settleName) {
        uni.showToast({
            title: '请输入结算名称',
            icon: 'none'
        })
        return
    }
    
    submitting.value = true
    try {
        let result
        if (isEditingSettle.value && currentSettle.value) {
            result = await MatchScheduleSettleAPI.edit({
                matchScheduleSettleId: settleForm.value.matchScheduleSettleId,
                settleType: settleType,
                settleName: settleName,
                settleDesc: String(settleForm.value.settleDesc || '').trim()
            })
        } else {
            result = await MatchScheduleSettleAPI.create({
                settleType: settleType,
                settleName: settleName,
                settleDesc: String(settleForm.value.settleDesc || '').trim()
            })
        }

        if (result.code === 0) {
            uni.showToast({
                title: isEditingSettle.value ? '更新成功' : '创建成功',
                icon: 'success'
            })
            
            // 清除编辑状态
            isAddingNewSettle.value = false
            editingSettleId.value = null
            isEditingSettle.value = false
            currentSettle.value = null
            resetSettleForm()
            
            loadSettleList()
        } else {
            throw new Error(result.msg || (isEditingSettle.value ? '更新失败' : '创建失败'))
        }
    } catch (error) {
        console.error('保存结算方式失败:', error)
        uni.showToast({
            title: error.message || '保存失败',
            icon: 'none'
        })
    } finally {
        submitting.value = false
    }
}

// 删除结算方式
const deleteSettle = (settle) => {
    currentDeleteSettle.value = settle
    showDeleteConfirm.value = true
}

// 确认删除
const confirmDelete = async () => {
    if (!currentDeleteSettle.value) return
    
    const settleId = currentDeleteSettle.value.id
    try {
        const result = await MatchScheduleSettleAPI.remove({
            matchScheduleSettleId: settleId
        })

        if (result.code === 0) {
            uni.showToast({
                title: '删除成功',
                icon: 'success'
            })
            showDeleteConfirm.value = false
            currentDeleteSettle.value = null
            loadSettleList()
        } else {
            throw new Error(result.msg || '删除失败')
        }
    } catch (error) {
        console.error('删除结算方式失败:', error)
        uni.showToast({
            title: error.message || '删除失败',
            icon: 'none'
        })
    }
}

// 页面加载时获取数据
onMounted(() => {
    loadSettleList()
})
</script>
<style lang="scss" scoped>
.view-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: calc(100vh - 65rpx);
    padding: 0 20rpx;
    overflow: hidden;


    .form-label {
        font-size: 12rpx;
        color: #333;
    }
    
    .settle-id-disabled {
        color: #999 !important;
        font-size: 14rpx;
    }

    &-right {
        flex: 1;
        height: 100%;
        overflow: hidden;
        position: relative;

        &-add {
            z-index: 1000;
            position: absolute;
            color: #fff;
            top: 8rpx;
            left: 10rpx;
            font-size: 12rpx;
            border-bottom: 1rpx solid #eeeeee;

        }

        &-list {
            padding: 10rpx;
            overflow: auto;
            height: calc(100% - 60rpx);

            &-add {
                background: #FFF9E6;
            }
            
            &-item-editing {
                background: #FFF9E6;
                border: 2rpx solid #3D85EC;
            }

            &-item {
                background: #F0F0E4;
                border-radius: 10rpx;
                padding: 10rpx;
                margin-bottom: 10rpx;
                font-size: 14rpx;

                &-empty {
                    text-align: center;
                    margin-top: 80rpx;
                }


                .next-button {
                    display: flex;
                    justify-content: end;
                    align-items: center;
                    margin-top: 10rpx;

                    &-item1,
                    &-item2 {
                        width: 108rpx;
                        height: 30rpx;
                        font-size: 14rpx;
                        display: flex;
                        justify-content: center;
                        align-items: center;
                        padding-bottom: 4rpx;
                        color: #fff;
                    }


                    &-item1 {
                        background: url('/static/buttons/button2-1.png') no-repeat center center;
                        background-size: 100% 100%;
                        margin-right: 10rpx;
                    }

                    &-item2 {
                        background: url('/static/buttons/button7.png') no-repeat center center;
                        background-size: 100% 100%;
                    }
                }

                .next-row {
                    display: flex;
                    //   justify-content: space-between;
                    align-items: center;
                    margin-top: 10rpx;

                    view {
                        width: 50%;
                        display: flex;
                        align-items: center;
                    }
                    
                    view[style*="width: 100%"] {
                        width: 100% !important;
                    }

                    text {
                        display: inline-block;
                        font-size: 14rpx;
                        color: #99A1A4;
                        width: 70rpx;
                        text-align: right;
                        flex-shrink: 0;
                    }
                }

                .form-input {
                    flex: 1;
                    height: 30rpx;
                    padding: 0 5rpx;
                    background: #fff;
                    border-radius: 4rpx;
                    font-size: 12rpx;
                    margin-left: 10rpx;
                    margin-right: 20rpx;
                    box-sizing: border-box;
                }
                
                .form-textarea {
                    flex: 1;
                    min-height: 60rpx;
                    padding: 5rpx;
                    background: #fff;
                    border-radius: 4rpx;
                    font-size: 12rpx;
                    margin-left: 10rpx;
                    margin-right: 20rpx;
                    box-sizing: border-box;
                    resize: none;
                }
            }
        }
    }

}
</style>
